<?php

namespace App\Listeners;

use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\Auth;

class QueryListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  QueryExecuted  $event
     * @return void
     */
    public function handle(QueryExecuted $event)
    {
        $sql = str_replace("?", "'%s'", $event->sql);
        $log = vsprintf($sql, $event->bindings);
        # select和非select sql 单独记录日志
        //更新后台操作用户最后活动时间字段 不计入日志。
        if(strpos($sql, 'last_actived_at') != false) {
            return;
        }
        $logDirSelect = storage_path('sql/select');
        if(! is_dir($logDirSelect)) {
            mkdir($logDirSelect, 0777, true);
        }
        $logDirUpdate = storage_path('sql/update');
        if(! is_dir($logDirUpdate)) {
            mkdir($logDirUpdate, 0777, true);
        }
        if('select' == strtolower(substr($log , 0 , 6))){
            $file = $logDirSelect . '/sql-' .date('Y-m-d') . '.log';
        } else {
            $file = $logDirUpdate . '/sql-' .date('Y-m-d') . '.log';
        }
        $user = Auth::getUser();
        $userId = 0;
        $userName = 'unLogin';
        if($user) {
            $userId = $user->id;
            $userName = $user->username;
        }
        $logLinePrefix = sprintf("[%s][%s-%s] ", date('Y-m-d H:i:s'), $userId, $userName);
        file_put_contents($file, $logLinePrefix . $log . ';' . PHP_EOL, FILE_APPEND);
    }
}
